package com.yk._01多线程买票程序;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.TimeUnit;

public class 传统的synchronized {

    public static void main(String[] args) {
        Ticket ticket = new Ticket(50);

        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                ticket.saleTicket();
            }
        },"窗口A").start();
        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                ticket.saleTicket();
            }
        },"窗口B").start();
        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                ticket.saleTicket();
            }
        },"窗口C").start();

    }

}

@Data
@NoArgsConstructor
@AllArgsConstructor
class Ticket{
    private int num;

    public synchronized void saleTicket() {
        try {
            TimeUnit.NANOSECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (num > 0) {
            num--;
            System.out.println(Thread.currentThread().getName() + " 售票成功 剩余票数 == " + num);
        }
    }
}